<template>
  <div class="camera-container">
    <!-- 左侧表单 -->
    <div class="camera-form">
      <h2 class="form-title">Capture Tools</h2>

      <!-- 路径选择 -->
      <el-form :model="captureForm" label-width="100px">
        <el-form-item label="Path">
          <el-select
            v-model="selectedPathId"
            placeholder="Select camera path"
            style="width: 100%"
            @change="handlePathChange"
          >
            <el-option
              v-for="path in pathList"
              :key="path.id"
              :label="path.name"
              :value="path.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="Interpolation">
          <el-input-number
            v-model="captureForm.interpolation"
            :min="0"
            :step="1"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="Modalities">
          <el-checkbox-group v-model="captureForm.modalities">
            <el-checkbox :label="0">Normal</el-checkbox>
            <el-checkbox :label="1">Fog</el-checkbox>
            <el-checkbox :label="2">Snow</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item>
          <div class="button-group">
            <el-button
              type="primary"
              @click="handlePreview"
              :loading="previewLoading"
              :disabled="!selectedPathId || previewLoading"
            >
              Preview
            </el-button>
            <el-button
              type="success"
              @click="handleCapture"
              :loading="captureLoading"
              :disabled="!selectedPathId || captureLoading"
            >
              Capture
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 右侧画布 -->
    <div class="camera-canvas" :style="backgroundStyle" ref="canvasContainer">
      <canvas ref="canvas"></canvas>
      <!-- 点位图标容器 -->
      <div class="points-container">
        <template v-if="selectedPath">
          <!-- 连接线 -->
          <svg class="path-lines">
            <path
              :d="getPathLines"
              stroke="#409EFF"
              stroke-width="2"
              fill="none"
              stroke-dasharray="5,5"
            />
          </svg>

          <!-- 点位图标 -->
          <div
            v-for="(point, index) in selectedPath.views"
            :key="index"
            class="point-icon"
            :style="{
              left: `${point.position.x * 100}%`,
              top: `${point.position.y * 100}%`,
              transform: `translate(-50%, -50%) rotate(${point.rotation.yaw}deg)`
            }"
          >
            <div class="icon-wrapper">
              <el-icon :size="20" color="#409EFF">
                <VideoCamera />
              </el-icon>
            </div>
            <div class="point-label">{{ index + 1 }}</div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed, onBeforeUnmount} from 'vue'
import { VideoCamera } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {cameraList, capturePreview, captureStart, captureStatus, getCaptureStatus, getMap} from '../api'

const canvas = ref(null)
const canvasContainer = ref(null)
const backgroundStyle = ref({})
const pathList = ref([])
const selectedPathId = ref(null)
const selectedPath = ref(null)
const previewLoading = ref(false)
const captureLoading = ref(false)

// 表单数据
const captureForm = reactive({
  interpolation: 0,
  modalities: []
})

// 轮询间隔（毫秒）
const POLL_INTERVAL = 1000

// 获取背景图片
function getBackgroundImage() {
  getMap().then(res => {
    if (res.success) {
      backgroundStyle.value = {
        backgroundImage: `url(${res.image})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }
    }
  })
}

// 获取路径列表
function getCameraList() {
  cameraList().then(res => {
    if (res.success) {
      pathList.value = res.data
    }
  })
}

// 处理路径选择
function handlePathChange(pathId) {
  const path = pathList.value.find(p => p.id === pathId)
  selectedPath.value = JSON.parse(JSON.stringify(path))
}

// 轮询预览状态
async function pollPreviewStatus() {
  try {
    const res = await getCaptureStatus()

    if (res.success && res.isReady === true) {
      previewLoading.value = false
      ElMessage.success('Preview is now available')
      return true
    }
    return false
  } catch (error) {
    console.error('Error polling preview status:', error)
    return false
  }
}

// 轮询捕获状态
async function pollCaptureStatus(taskId) {
  try {
    const res = await captureStatus(taskId)

    if (res.success) {
      if (res.status === 'completed') {
        captureLoading.value = false
        ElMessage.success('Capture completed')
        // 下载文件
        window.location.href = res.downloadUrl
        return true
      }
    }
    return false
  } catch (error) {
    console.error('Error polling capture status:', error)
    return false
  }
}

// 开始轮询
async function startPolling(pollFunction, loadingRef) {
  while (loadingRef.value) {
    const shouldStop = await pollFunction()
    if (shouldStop) break
    await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL))
  }
}

// 处理预览
function handlePreview() {
  if (!selectedPathId.value) {
    ElMessage.warning('Please select a path first')
    return
  }
  previewLoading.value = true
  capturePreview({
    path: selectedPathId.value,
    interpolation: captureForm.interpolation
  }).then(res => {
    if (res.success) {
      // 预览成功
      startPolling(() => pollPreviewStatus(), previewLoading)
    } else {
      previewLoading.value = false
      ElMessage.error(res.message || 'Preview failed')
    }
  })
}

// 处理捕获
function handleCapture() {
  if (!selectedPathId.value) {
    ElMessage.warning('Please select a path first')
    return
  }

  captureLoading.value = true
  captureStart({
    path: selectedPathId.value,
    interpolation: captureForm.interpolation,
    modalities: captureForm.modalities
  }).then(res => {
    if (res.success) {
      // 捕获成功
      startPolling(() => pollCaptureStatus(res.taskId), captureLoading)
    } else {
      captureLoading.value = false
      ElMessage.error(res.message || 'Capture failed')
    }
  })
}

// 计算路径连接线
const getPathLines = computed(() => {
  if (!selectedPath.value.views.length) return ''

  const container = canvasContainer.value
  if (!container) return ''
  const width = container.clientWidth
  const height = container.clientHeight

  const points = selectedPath.value.views.map(point => ({
    x: (point.position.x * width),
    y: (point.position.y * height)
  }))

  if (points.length < 2) return ''

  let path = `M ${points[0].x} ${points[0].y}`
  for (let i = 1; i < points.length; i++) {
    path += ` L ${points[i].x} ${points[i].y}`
  }

  // 如果是闭合路径且点数大于2，连接首尾
  if (selectedPath.value.isClosed && points.length > 2) {
    path += ` L ${points[0].x} ${points[0].y}`
  }

  return path
})

onMounted(() => {
  resizePreview()
  getBackgroundImage()
  getCameraList()

  // 监听窗口大小变化，重新调整画布大小
  window.addEventListener('resize', () => {
    resizePreview()
  })
})

function resizePreview() {
  if (canvasContainer.value) {
    canvasContainer.value.style.width = canvasContainer.value.offsetHeight + 'px'
  }
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizePreview)
})
</script>

<style scoped>
/* 复用 Camera.vue 的样式 */
.camera-container {
  display: flex;
  height: 100%;
  gap: 20px;
  overflow: hidden;
}

.camera-form {
  width: 600px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  overflow-y: auto;
  overflow-x: hidden;
}

.camera-canvas {
  height: 100%;
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  position: relative;
}

.button-group {
  display: flex;
  gap: 10px;
}

.points-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.point-icon {
  position: absolute;
  cursor: pointer;
  pointer-events: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  z-index: 1;
}

.icon-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.point-label {
  font-size: 12px;
  color: #fff;
  background: #409EFF;
  padding: 2px 6px;
  border-radius: 10px;
  pointer-events: none;
}

.path-lines {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}

svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: visible;
}
</style>
